package com.mfc.education.service.trade.controller.api;

import com.github.wxpay.sdk.WXPayUtil;
import com.mfc.education.common.base.result.R;
import com.mfc.education.common.base.result.ResultCodeEnum;
import com.mfc.education.service.trade.entity.Order;
import com.mfc.education.service.trade.service.OrderService;
import com.mfc.education.service.trade.service.WeixinPayService;
import com.mfc.education.service.trade.util.StreamUtils;
import com.mfc.education.service.trade.util.WeixinPayProperties;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mfc
 * @since 2021/10/4
 */
@RestController
@RequestMapping("/api/trade/weixin-pay")
@Api(description = "网站微信支付")
 //跨域
@Slf4j
public class ApiWeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private WeixinPayProperties weixinPayProperties;

    @Autowired
    private OrderService orderService;

    @GetMapping("create-native/{orderNo}")
    public R createNative(@PathVariable String orderNo, HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        Map<String, Object> map = weixinPayService.createNative(orderNo, remoteAddr);
        return R.ok().data(map);
    }

    @PostMapping("callback/notify")
    public String wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        log.info("\n callback/notify 被调用");

        ServletInputStream inputStream = request.getInputStream();
        String notifyXml = StreamUtils.inputStream2String(inputStream, "UTF-8");

        log.info("\n notifyXml =\n" + notifyXml);

        // 验签：验证签名是否正确
        if (WXPayUtil.isSignatureValid(notifyXml, weixinPayProperties.getPartnerKey())) {
            Map<String, String> resultMap = WXPayUtil.xmlToMap(notifyXml);

            //判断支付结果
            String resultCode = resultMap.get("result_code");
            if ("SUCCESS".equals(resultCode)) {
                String orderNo = resultMap.get("out_trade_no");
                Order order = orderService.getOrderByOrderNo(orderNo);
                // 金额校验
                String totalFee = resultMap.get("total_fee");
                if (order != null && order.getTotalFee().intValue() == Integer.parseInt(totalFee)) {
                    //改变订单状态
                    //接口调用的幂等性:无论接口被调用多少次，最后所影响的结果都是一致的
                    if (order.getStatus() == 0) {
                        orderService.updateOrderStatus(resultMap);

                    }
                    //支付成功:给微信发送我已接收通知的响应
                    // 创建响应对象
                    HashMap<String, String> returnMap = new HashMap<>();
                    returnMap.put("return_code", "SUCCESS");
                    returnMap.put("return_msg", "OK");
                    String returnXml = WXPayUtil.mapToXml(returnMap);
                    response.setContentType("text/xml");
                    log.info("已接收通知");

                    return returnXml;

                }
            }


        }
        //创建响应对象:微信接收到校验失败的结果后，会反复的调用当前回调函数
        HashMap<String, String> returnMap = new HashMap<>();
        returnMap.put("return_code", "FAIL");
        returnMap.put("return_msg", "");
        String returnXml = WXPayUtil.mapToXml(returnMap);
        response.setContentType("text/xml");
        log.info("校验失败");

        return returnXml;


    }


}